//
//  BHCircleChoseRelationViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/7/14.
//

import UIKit

protocol BHCircleChoseRelationViewControllerDelegate {
    func didChoseRelation(model: BHCirclePublishRelationInfoModel)
}

class BHCircleChoseRelationViewController: BHBaseViewController {

    var delegate: BHCircleChoseRelationViewControllerDelegate?
    
    
    lazy var navigationBar_view: BHCircleRelationNavigationBar = {
        let view = BHCircleRelationNavigationBar.loadFromXib()
        view.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: BHCircleRelationNavigationBar.secHeight)
        return view
    }()
    
    lazy var tableView: UITableView = {
        let view = UITableView.buildTableView(style: .plain)
        view.frame = CGRect(x: 0, y: BHCircleRelationNavigationBar.secHeight, width: UIScreen.width, height: UIScreen.height-BHCircleRelationNavigationBar.secHeight)
        view.delegate = self
        view.dataSource = self
        view.backgroundColor = .color_f8f8f8
        view.regiseterNib(nibName: "BHCircleChoseStadiumCell")
        return view
    }()
    
    /**0运动场馆  1赛事  2趣玩*/
    var type: Int = 0
    fileprivate var pageArray: [Int] = [1,1,1]
    fileprivate var totalArray: [Int] = [0,0,0]
    fileprivate var searchKeyArray: [String] = ["","",""]
    fileprivate var allArray: [[BHCirclePublishRelationInfoModel]] = [[],[],[]]
    fileprivate var searchKey: String = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.bh_navigationBar.removeFromSuperview()
        self.view.addSubview(self.navigationBar_view)
        self.view.addSubview(self.tableView)
        
        self.navigationBar_view.didChangeIndexActBlock = { [weak self] index in
            self?.view.endEditing(true)
            self?.type = index
            self?.page = self?.pageArray[index] ?? 1
            let total = self?.totalArray[index] ?? 0
            self?.searchKey = self?.searchKeyArray[index] ?? ""
            self?.navigationBar_view.search_textFiled.text = self?.searchKey ?? ""
            let array: [BHCirclePublishRelationInfoModel] = self?.allArray[index] ?? []
            if array.count == 0 {
                self?.relationListService()
            }else {
                self?.tableView.reloadData()
                
                if array.count >= total {
                    self?.tableView.endLoadWithNoMoreData(true)
                }else {
                    self?.tableView.endLoadWithNoMoreData(false)
                }
            }
        }
        
        self.navigationBar_view.back_btn.addBtnAction(action: {[weak self] (_) in
            self?.navigationController?.popViewController(animated: true)
        }, for: .touchUpInside)
        
        self.relationListService()
        
        // 搜索
        self.navigationBar_view.goSearchBlock = { [unowned self] text in
            self.searchKey = text
            self.searchKeyArray[self.type] = text
            self.page = 1
            self.pageArray[self.type] = 1
            
            self.relationListService()
        }
    }
    


}
extension BHCircleChoseRelationViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let array: [BHCirclePublishRelationInfoModel] = self.allArray[self.type]
        return array.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 82
    }
 
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
    
}

extension BHCircleChoseRelationViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView.init(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 10))
        view.backgroundColor = .color_f8f8f8
        return view
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "BHCircleChoseStadiumCell", for: indexPath) as! BHCircleChoseStadiumCell
        let array: [BHCirclePublishRelationInfoModel] = self.allArray[self.type]
        let model: BHCirclePublishRelationInfoModel = array[indexPath.row]
        
        if self.type == 2 {
            cell.icon_imageView.isHidden = true
            cell.name_label_leading.constant = -50
            cell.name_label.text = model.relationName
            cell.des_label.text = "开始日期：\(model.beginTime)"
            cell.distabce_label.text = "\(model.distance) \(model.areaName)"
        }else {
            cell.icon_imageView.isHidden = false
            cell.name_label_leading.constant = 10
            cell.icon_imageView.sd_setImage(with: URL.init(string: model.relationPic), completed: nil)
            if self.type == 0 {
                cell.name_label.text = model.relationName
                cell.des_label.text = "\(model.cityName)/\(model.areaName)"
            }else {
                cell.name_label.text = model.relationName
                cell.des_label.text = "开始日期：\(model.beginTime)"
            }
            cell.distabce_label.isHidden = !BHLocationManager.shared.authed
            cell.distabce_label.text = "\(model.distance)km"
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let array: [BHCirclePublishRelationInfoModel] = self.allArray[self.type]
        let model: BHCirclePublishRelationInfoModel = array[indexPath.row]
        self.delegate?.didChoseRelation(model: model)
        self.navigationController?.popViewController(animated: true)
    }
}

// MARK: 获取列表
/**relationType 1.场馆 2.赛事 3.趣玩
 search  搜索关键词
 运动场馆*/
extension BHCircleChoseRelationViewController {
    func relationListService()  {
        
        let dic = self.appendDic()
        let manager = BHHTTPClient.init()
        manager.get(url: String.circle_publish_relation_url, paramters: dic) { (success, errorMsg, responseDic) in
            if success == true {
                let result = BHJsonTool.decodeDicFromDic(dic: responseDic, key: "result")
                let records = BHJsonTool.decodeArrayFromDic(dic: result, key: "records")
                let total = BHJsonTool.decodeIntFromDic(dic: result, key: "total")
                let currentArray = self.allArray[self.type]
                var temp: [BHCirclePublishRelationInfoModel] = []
                if self.page == 1 {
                    self.tableView.endLoadWithNoMoreData(false)
                }else {
                    temp.append(contentsOf: currentArray)
                }
                self.totalArray[self.type] = total
                for dic in records {
                    let model = BHCirclePublishRelationInfoModel.init()
                    model.parseDic(dic as! [String:Any])
                    model.type = self.type+1
                    temp.append(model)
                }
                self.allArray[self.type] = temp
                if temp.count >= total {
                    self.tableView.endLoadWithNoMoreData(true)
                }
                self.tableView.reloadData()
                
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
    }
    
    func appendDic() -> [String:Any] {
        var dic: [String:Any] = [:]
        dic["pageNo"] = self.page
        dic["pageSize"] = "10"
        dic["relationType"] = "\(self.type+1)"
        dic["search"] = self.searchKey
        dic["longitude"] = BHLocationManager.shared.longitude
        dic["latitude"] = BHLocationManager.shared.latitude
        return dic
    }
}
